<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
#TODO
//******************************************封装函数*******************************************
require_once(APP_PATH . 'tname.php');

/**
 * 将序列化的信息存入到数据库中，进行转换  2017-10-15
 * @param mixed $info 信息    $type 0为序列化，1为反序列化
 */
function serializeMysql($info, $type = 0)
{
    if ($type == 0) {
        return addslashes(serialize($info));
    } else {
        return unserialize(stripslashes($info));
    }
}


/**
 * ajax成功返回 2017-10-15
 * @param string $data 数据数组 $msg 提示信息   $url 跳转url  $attach 附加数据
 */
function ajaxSuccess($data = '', $msg = '操作成功', $url = '', $attach = '')
{
    $data = array(
        'ret' => 1,
        'data' => $data,
        'msg' => $msg,
        'url' => $url,
        'attach' => $attach
    );
    return $data;
}

/**
 * ajax失败返回 2017-10-15
 * @param string $msg
 */
function ajaxFalse($msg = '操作失败', $url = '', $attach = '')
{
    $data = array(
        'ret' => 0,
        'msg' => $msg,
        'url' => $url,
        'attach' => $attach
    );
    return $data;
}

/**
 * 将信息记录到文件中 2017-10-15
 * $info 需要打印的信息
 */
function logs($info)
{
    $path = RUNTIME_PATH . 'log/' . date("Ym") . '/' . date("d_H_i_s") . '.log';
    $f = fopen($path, 'a');
    $file = fwrite($f, print_r($info, true));
    $file = fwrite($f, print_r(PHP_EOL . PHP_EOL, true));
}

/**
 * API接口明细记录    2017-10-15
 * @param $classify 模块、$type 变动类型、$url 接口地址、$content 发送内容、$result 返回值
 */
function apilog($uid, $classify, $type, $url, $content, $result)
{
    $destination = RUNTIME_PATH . 'log' . DS . date("Ym") . DS . date('d') . 'api.log';
    $path = dirname($destination);
    !is_dir($path) && mkdir($path, 0755, true);

    if (is_file($destination) && floor(2097152) <= filesize($destination)) {
        rename($destination, dirname($destination) . DS . time() . '-' . basename($destination));
    }

    $now = '[ 创建时间 ] ' . date("Y-m-d H:i:s");
    $uid = '[ UID ] ' . $uid;
    $localurl = '[ 运行链接 ] ' . get_url();
    $classify = '[ 模块 ] ' . $classify;
    $type = '[ 类型 ] ' . $type;
    $url = '[ 接口链接 ] ' . $url;
    $message = "---------------------------------------------------------------\r\n{$now}\r\n{$uid}\r\n{$localurl}\r\n{$classify}\r\n{$type}\r\n{$url}\r\n";

    $f = fopen($destination, 'a');
    $file = fwrite($f, print_r($message . '[ 接口内容 ] ', true));
    $file = fwrite($f, print_r($content, true));
    $file = fwrite($f, print_r("\r\n[ 接口返回结果 ] ", true));
    $file = fwrite($f, print_r($result, true));
    $file = fwrite($f, print_r("\r\n\r\n", true));
    return true;
}

/**
 * 随机字符串生成    2017-10-15
 * @param $length 字符串长度
 */
function createnoncestr($length = 16)
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

/**
 * 生成验证码    2017-10-15
 */
function createverifycode($length = 4)
{
    $number = "";
    for ($i = 0; $i < $length; $i++) {
        $number .= rand(0, 9);
    }
    return $number;
}

/**
 * xml格式转数组    2017-10-15
 */
function xmltoarray($xml)
{
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}

/**
 * 数据XML编码  不含CDATA 2017-10-15
 * @param  object $xml XML对象    mixed  $data 数据    string $item 数字索引时的节点名称
 */
function data2xml($xml, $data, $item = 'item')
{
    foreach ($data as $key => $value) {
        /* 指定默认的数字key */
        is_numeric($key) && $key = $item;

        /* 添加子元素 */
        if (is_array($value) || is_object($value)) {
            $child = $xml->addChild($key);
            $this->data2xml($child, $value, $item);
        } else {
            $child = $xml->addChild($key, $value);
        }
    }
}

/**
 * 根据经纬度计算距离    2017-10-15
 * @param $lat经度 $lng维度
 */
function getdistance($lat1, $lng1, $lat2, $lng2)
{
    $EARTH_RADIUS = 6378.137;
    $radLat1 = $this->rad($lat1);
    $radLat2 = $this->rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = $this->rad($lng1) - $this->rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) +
            cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s, 3);//千米为单位，3位小数
    return $s;
}

/**
 * rad  2017-10-15
 */
function rad($d)
{
    return $d * 3.1415926535898 / 180.0;
}

/**
 * 转换周几    2017-10-15
 * @param $week 周几数字格式
 */
function toweek($week)
{
    switch ($week) {
        case 0:
            return '日';
        case 1:
            return '一';
        case 2:
            return '二';
        case 3:
            return '三';
        case 4:
            return '四';
        case 5:
            return '五';
        case 6:
            return '六';
        default:
            return false;
    }
}

/**
 * 时间细分    2017-10-15
 * @param $createtime 时间戳
 */
function time_refine($createtime)
{
    $time = time() - $createtime;
    $days = intval($time / 86400);
    //计算小时数
    $remain = $time % 86400;
    $hours = intval($remain / 3600);
    //计算分钟数
    $remain = $remain % 3600;
    $mins = intval($remain / 60);
    //计算秒数
    $secs = $remain % 60;
    if ($days != 0) {
        $time = $days . '天前';
    } elseif ($hours != 0) {
        $time = $hours . '小时前';
    } elseif ($mins != 0) {
        $time = $mins . '分钟前';
    } else {
        $time = $secs . '秒前';
    }
    return $time;
}

/**
 * 获取当前全部url    2017-10-15
 */
function get_url()
{
    if (!input('?server.REQUEST_SCHEME')) {
        $protocol = input('server.SERVER_PORT') == 443 ? "https:" : "http";
    } else {
        $protocol = input('server.REQUEST_SCHEME');
    }
    return $protocol . '://' . input('server.HTTP_HOST') . input('server.REQUEST_URI');
}

/**
 * 获取当前的网址加目录信息    2017-10-15
 */
function get_domain()
{
    $base = request()->root();
    $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
    if ('' != $root) {
        $root = '/' . ltrim($root, '/');
    }
    if (!input('?server.REQUEST_SCHEME')) {
        $protocol = input('server.SERVER_PORT') == 443 ? "https:" : "http";
    } else {
        $protocol = input('server.REQUEST_SCHEME');
    }
    return $protocol . '://' . input('server.HTTP_HOST') . $root;
}

/**
 * 获取当前或者服务器端的IP    2017-10-15
 */
function get_client_ip($type = 1)
{
    if ($type == 1) {
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
    } else if ($type == 2) {
        return isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '0.0.0.0';
    }
}

/**
 * 系统非常规MD5加密方法    2017-10-15
 * @param  string $str 要加密的字符串
 */
function think_ucenter_md5($str, $key = 'ThinkUCenter')
{
    return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 检测手机号    2017-10-15
 */
function check_mobilephone($mobilehone = '')
{
    if (preg_match("/1[34578]{1}\d{9}$/", $mobilehone)) {
        return true;
    } else {
        return false;
    }
}

/**
 * POST请求    2017-10-15
 */
function httpdata($url, $data)
{

    $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    //$data = JSON($data, false);

    $ch = curl_init();
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $status = curl_exec($ch);
    curl_close($ch);
    $res = json_decode($status, true);
    return $res;
}

/**
 * GET请求    2017-10-15
 */
function https_request($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return 'ERROR ' . curl_error($curl);
    }
    curl_close($curl);
    $data = json_decode($data, true);
    return $data;
}

//******************************************微信接口*******************************************
#TODO
/**
 * 获取access_token  2017-10-15
 * @param $uid
 */
function getaccesstoken($uid)
{
    $config = db(\tname::weixin_config)->where('uid', $uid)->find();
    if (($config['access_token'] == null) || ($config['access_time'] + 7200 < time())) {
        $Token = new \wechat\Token();
        $result = $Token->gettoken($config['appid'], $config['appsecret'], array('uid' => $uid));

        if (isset($result['access_token'])) {
            $configdata = array(
                'access_token' => $result['access_token'],
                'access_time' => time(),
            );
            db(\tname::weixin_config)->where('uid', $uid)->update($configdata);
        }

        isset($result['access_token']) ? $access_token = $result['access_token'] : $access_token = '';
    } else {
        $access_token = $config['access_token'];
    }

    return $access_token;
}

/**
 * 获得jsapi_ticket 临时票据    2017-10-15
 * @param $uid
 */
function getjsapiticket($uid)
{
    $filename = './static/wechat/common/json/jsapi_ticket' . $uid . '.json';
    file_exists($filename) && $data = json_decode(file_get_contents($filename));

    if (!isset($data) || $data->expire_time < time()) {
        $access_token = getaccesstoken($uid);
        $Token = new \wechat\Token();
        $result = $Token->getjsapi($access_token, array('uid' => $uid));
        if (isset($result['ticket'])) {
            $data = (object)array();
            $data->expire_time = time() + 7000;
            $data->jsapi_ticket = $result['ticket'];

            file_put_contents($filename, json_encode($data));
        }
        isset($result['ticket']) ? $ticket = $result['ticket'] : $ticket = '';
    } else {
        $ticket = $data->jsapi_ticket;
    }

    return $ticket;
}

/**
 * 获取微信生成永久二维码        2017-10-15
 * @param $sceneid 布景值 $type 1为字符串 2为整型
 */
function getticket($uid, $sceneid, $type = 1)
{
    if ($type == 1) {
        $data = array(
            'action_name' => 'QR_LIMIT_STR_SCENE',
            'action_info' => array(
                'scene' => array(
                    'scene_str' => $sceneid,
                ),
            ),
        );
    } else {
        $data = array(
            'action_name' => 'QR_LIMIT_SCENE',
            'action_info' => array(
                'scene' => array(
                    'scene_id' => $sceneid,
                ),
            ),
        );
    }

    $access_token = getaccesstoken($uid);
    $Ticket = new \wechat\Ticket();
    $res = $Ticket->getticket($data, $access_token, array('uid' => $uid));

    return $res;
}

/**
 * 发送模板消息    2017-10-15
 * @param $data 特定格式数组
 */
function sendtemplate($uid, $data)
{
    $template['touser'] = $data['openid'];
    $template['template_id'] = $data['tid'];
    $template['url'] = $data['url'];
    foreach ($data['content'] as $key => $value) {
        $template['data'][$key] = array(
            'value' => $value,
            'color' => '#173177'
        );
    }
    $access_token = getaccesstoken($uid);
    $Message = new \wechat\Message();
    $Message->template($template, $access_token, array('uid' => $uid));
}

//******************************************其他接口*******************************************
#TODO
/**
 * 发送短信 生成短信日志    2017-10-15
 * @param $mobilephone 手机号  $content 短信内容 $type短信类型
 */
function sendmessage($uid, $mobilephone, $content, $type)
{
    $Message = new \zzymessage\Message();
    $result = $Message->sendmessage($mobilephone, $content, array('uid' => WID));

    $logdata = array(
        'uid' => $uid,
        'type' => $type,
        'mobilephone' => $mobilephone,
        'content' => $content,
        'result' => $result,
        'create_time' => time()
    );
    dataUpdate(\tname::data_message, $logdata);

    return $result;
}

//******************************************grand  cut-off rule*******************************************
#TODO
/**
 * 导出至excel表格        2017-10-15
 * @param: $fileName表格名字   $headArr表头  $data导出数据  $msg批注
 */
function getExcel($fileName, $headArr, $data, $msg)
{
    //对数据进行检验
    if (empty($data) || !is_array($data)) {
        die("data must be a array");
    }

    //检查文件名
    if (empty($fileName)) {
        die("filename must be existed");
    }

    //获取总列数
    $totalColumn = count($headArr);
    $charColumn = chr($totalColumn + 64);
    $date = date("Y-m-d", time());
    $fileName .= "_{$date}.xls";

    //创建PHPExcel对象
    $objPHPExcel = new \PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0);    //设置当前的sheet  操作第一个工作表
    $objActSheet = $objPHPExcel->getActiveSheet();    //添加数据
    $phpstyle = new \PHPExcel_Style_Color();

    //表头变颜色
    $objActSheet->getStyle('A1:' . $charColumn . '1')->getFont()->getColor()->setARGB($phpstyle::COLOR_BLUE);    //设置颜色

    //设置批注
    $objActSheet->getStyle('A2')->getFont()->getColor()->setARGB($phpstyle::COLOR_RED);
    $objActSheet->setCellValue('A2', $msg);    //给单个单元格设置内容
    $objActSheet->mergeCells('A2:' . $charColumn . '2');    //合并单元格

    //设置表头
    $key = ord("A");
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objActSheet->setCellValue($colum . '1', $v);
        $objActSheet->getColumnDimension($colum)->setWidth(20);
        $key++;
    }

    //写入数据
    $column = 3;
    foreach ($data as $key => $rows) {     //行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) {    // 列写入
            $j = chr($span);
            if ($keyName !== 'img') {
                $objActSheet->setCellValue($j . $column, $value);
            } elseif ($keyName == 'img') {
                $objActSheet->getRowDimension($column)->setRowHeight(60);    //设置行高
                $objDrawing = new \PHPExcel_Worksheet_Drawing();
                $objDrawing->setPath($value);
                $objDrawing->setWidth(50);
                $objDrawing->setHeight(50);
                $objDrawing->setCoordinates($j . $column);
                $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
            }
            $span++;
        }
        $column++;
    }

    //处理中文输出问题
    $fileName = iconv("utf-8", "gb2312", $fileName);

    //接下来当然是下载这个表格了，在浏览器输出就好了
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
}

/**
 * 获取表格数据   2017-10-15
 * @param: $fileName表格名字   $headArr表头  $data导出数据  $msg批注
 */
function getData($file_dir)
{
//    vendor('PHPExcel.PHPExcel');
    $PHPReader = new \PHPExcel_Reader_Excel2007();
    $PHPReader = new \PHPExcel_Reader_Excel5();


    if (!$PHPReader->canRead($file_dir)) {
        $PHPReader = new \PHPExcel_Reader_Excel5();
        if (!$PHPReader->canRead($file_dir)) {
            return array(0, '请上传文档');
        }
    }

    //载入文件
    $PHPExcel = $PHPReader->load($file_dir);

    //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
    $currentSheet = $PHPExcel->getSheet(0);

    //获取总行数
    $allRow = $currentSheet->getHighestRow();
    $allColumn = $currentSheet->getHighestColumn();
    $allColumn = ord($allColumn);

    for ($j = 2; $j <= $allRow; $j++) {
        for ($i = 65; $i <= $allColumn; $i++) {
            $colum = chr($i);
            $data[$j][$colum] = $PHPExcel->getActiveSheet()->getCell($colum . $j)->getValue();
        }
    }
    return array(1, $data);
}

/**
 * 数据统计    2017-10-15
 */
function account($uid, $type, $count = 1)
{
    $today = strtotime("today");

    $where['time'] = $today;
    $where['uid'] = $uid;
    $where['type'] = $type;
    $hascount = db(\tname::data_count)->where($where)->find();

    if (empty($hascount)) {
        $data = array(
            'uid' => $uid,
            'type' => $type,
            'time' => $today,
            'count' => $count,
        );
        $res = db(\tname::data_count)->where($where)->insert($data);
    } else {
        $res = db(\tname::data_count)->where($where)->setInc('count', $count);
    }
    if ($res) {
        return true;
    } else {
        return false;
    }
}


/**
 * 获得优惠券   2017-10-15
 * @param $openid 变动人员、$type 获得优惠券突降、$couponid 优惠券ID
 */
function getcoupon($uid, $openid, $type, $couponid = array())
{
    $couponList = db(\tname::coupon)->where(array('uid' => $uid, 'id' => array('in', $couponid)))->select();
    $vip = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->find();

    foreach ($couponList as $key => $value) {
        $data[] = array(
            'uid' => $uid,
            'openid' => $openid,
            'nickname' => $vip['nickname'],
            'type' => $type,
            'couponid' => $value['id'],
            'classify' => $value['classify'],
            'category' => $value['category'],
            'name' => $value['name'],
            'discount' => $value['discount'],
            'price' => $value['price'],
            'limit' => $value['limit'],
            'notice' => $value['notice'],
            'stime' => $value['stime'],
            'etime' => $value['etime'],
            'createtime' => time(),
        );
    }
    //添加至我的优惠券
    $res = db(\tname::coupon_mycoupon)->insertAll($data);
    if ($res) {
        db(\tname::coupon)->where(array('uid' => $uid, 'id' => array('in', $couponid)))->setInc('actualsales');
        db(\tname::coupon)->where(array('uid' => $uid, 'id' => array('in', $couponid)))->setInc('configsales');
        db(\tname::coupon)->where(array('uid' => $uid, 'id' => array('in', $couponid)))->setDec('number');
        $result['result_code'] = $res;
        $result['msg'] = '发送成功';
    } else {
        $result['result_code'] = 0;
        $result['msg'] = '请联系管理员';
    }
    return $result;
}


/**
 * php完美实现下载远程图片保存到本地   2017-10-15
 * @param: 文件url,保存文件目录,保存文件名称，使用的下载方式    当保存文件名称为空时则使用远程文件原来的名称
 * @date: 2017-05-13
 */
function getimage($url, $save_dir = '', $filename = '', $type = 0)
{
    if (trim($url) == '') {
        return array('file_name' => '', 'save_path' => '', 'error' => 1);
    }
    if (trim($save_dir) == '') {
        $save_dir = './';
    }
    if (trim($filename) == '') {//保存文件名
        $ext = strrchr($url, '.');
        if ($ext != '.gif' && $ext != '.jpg') {
            return array('file_name' => '', 'save_path' => '', 'error' => 3);
        }
        $filename = time() . $ext;
    }
    if (0 !== strrpos($save_dir, '/')) {
        $save_dir .= '/';
    }
    //创建保存目录
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return array('file_name' => '', 'save_path' => '', 'error' => 5);
    }

    //获取远程文件所采用的方法
    if ($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $img = curl_exec($ch);
        curl_close($ch);

    } else {
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
    }
    //$size=strlen($img);
    //文件大小

    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $img);
    fclose($fp2);
    unset($img, $url);
    return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
}

//******************************************非常规接口*******************************************
#TODO

/**
 * 更新数据库    2017-10-15
 * @param: $tablename 表名    $map 查询 $fieldname 字段 $afterchange 改后值
 */
function dataUpdate($tablename, $data)
{
    if (!isset($data['id']) || !$data['id']) {
        $data['create_time'] = time();
        $res = db($tablename)->insertGetId($data);
        if ($res !== false) {
            return $res;
        } else {
            return false;
        }
    } else {
        $res = db($tablename)->update($data);
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 余额变动    2017-10-15
 * @param $type 变动类型、$openid 变动人员、$money 变动数量、$infoid 关联信息ID、$change 1为加积分 2为减积分、$remark 预留字段
 */
function moneylog($uid, $type, $openid, $money = 0, $infoid = 0, $change = 1, $remark = '')
{
    if ($money <= 0) {
        return array(0, '变动余额必须大于0');
    }

    $vip_before = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->find();

    if ($change == 1) {
        $res = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->setInc('money', $money);
    } else {
        if ($vip_before['money'] < $money) {
            return array(0, '您现在只有' . $vip_before['money'] . '，请不要超过此值');
        }
        $res = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->setDec('money', $money);
    }
    if (!$res) {
        return array(0, '操作失败');
    }

    $vip = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->find();
    $data = array(
        'uid' => $uid,
        'openid' => $openid,
        'nickname' => $vip['nickname'],
        'info_id' => $infoid,
        'type' => $type,
        'change' => $change,
        'money' => $money,
        'cur_money' => $vip['money'],
        'remark' => $remark
    );
    $res1 = dataUpdate(\tname::money_log, $data);
    if ($res1) {
        return array(1);
    } else {
        return array(0, '操作失败');
    }

}

/**
 * 积分变动    2017-10-15
 * @param $type 变动类型、$openid 变动人员、$integral 变动数量、$infoid 关联信息ID、$change 1为加积分 2为减积分、$remark 预留字段
 */
function integrallog($uid, $type, $openid, $integral = 0, $infoid = 0, $change = 1, $remark = '')
{
    if ($integral <= 0) {
        return array(0, '变动积分必须大于0');
    }

    $vip_before = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->find();

    if ($change == 1) {
        $res = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->setInc('integral', $integral);
    } else {
        if ($vip_before['integral'] < $integral) {
            return array(0, '您现在只有' . $vip_before['integral'] . '积分，请不要超过此值');
        }
        $res = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->setDec('integral', $integral);
    }

    if (!$res) {
        return array(0, '操作失败');
    }

    $vip = db(\tname::vip)->where(array('uid' => $uid, 'openid' => $openid))->find();
    $data = array(
        'uid' => $uid,
        'openid' => $openid,
        'nickname' => $vip['nickname'],
        'info_id' => $infoid,
        'type' => $type,
        'change' => $change,
        'integral' => $integral,
        'cur_integral' => $vip['integral'],
        'remark' => $remark
    );
    $res1 = dataUpdate(\tname::integral_log, $data);

    if ($res1) {
        return array(1);
    } else {
        return array(0, '操作失败');
    }
}

/**
 * 交互记录    2017-10-15
 * @param $openid 浏览人 $classify模块    $type 类型  $infoid 关联ID $remark 备注
 */
function interactive($uid, $openid, $classify, $type, $infoid, $remark = '')
{
    $data = array(
        'uid' => $uid,
        'openid' => $openid,
        'classify' => $classify,
        'type' => $type,
        'info_id' => $infoid,
        'create_time' => time(),
        'remark' => $remark
    );
    $res = db(\tname::data_interactive)->insert($data);
    if ($res) {
        return $res;
    } else {
        return 0;
    }
}

/**
 * 交互记录删除    2017-10-15
 * @param $map筛选条件
 */
function interactivedel($map)
{
    $res = db(\tname::data_interactive)->where($map)->delete();
    if ($res) {
        return $res;
    } else {
        return 0;
    }
}

/**
 * 判断是否有此交互    2017-10-15
 * @param $map筛选条件
 */
function interactivehas($map)
{
    $data = db(\tname::data_interactive)->where($map)->find();
    if (empty($data)) {
        return 0;
    } else {
        return $data['id'];
    }
}

/**
 * 计算给定交互数量    2017-10-15
 * @param $map筛选条件
 */
function interactivecount($map)
{
    $count = db(\tname::data_interactive)->where($map)->count();
    return $count;
}

/**
 * 生成随机订单编号    2017-10-15
 * @param $length 字符串长度
 */
function createOrdernumber($tablename)
{
    $number = date('Ymd');
    for ($i = 0; $i < 4; $i++) {
        $number .= rand(0, 9);
    }
    $res = db($tablename)->where(array('ordernumber' => $number))->find();   //保证生成的订单编号不会重复
    if ($res) {
        createOrdernumber($tablename);
    } else {
        return $number;
    }
}

/**
 * 建立三级分销关系   2017-10-15
 * @param $myopenid 我的微信号 $lastvipid 我的上一级的会员ID
 */
function distributionBuildrelation($uid, $myopenid, $first_vip_id = 0)
{
    $mytrader = db(\tname::distribution_mytrader)->where(array('uid' => $uid, 'openid' => $myopenid))->find();

    if (!empty($mytrader)) {    //如果已经建立过，不会重复建立
        return array(0, '已经建立过关系');
    }
    if (!$first_vip_id) {
        $first_vip_id = 0;
    }

    $data = array(
        'uid' => $uid,
        'openid' => $myopenid,
        'create_time' => time(),
    );
    if ($first_vip_id) {
        $first_vip = db(\tname::vip)->where(array('uid' => $uid, 'id' => $first_vip_id))->find();

        $second_vip = db(\tname::distribution_mytrader)->where(array('uid' => $uid, 'openid' => $first_vip['openid']))->find();
        $data['first_vip_id'] = $first_vip_id;
        $data['second_vip_id'] = $second_vip['first_vip_id'];
        $data['third_vip_id'] = $second_vip['second_vip_id'];
        if ($second_vip['all_prev_id']) {
            $data['all_prev_id'] = $second_vip['all_prev_id'] . ',' . $first_vip_id;
        } else {
            $data['all_prev_id'] = $first_vip_id;
        }
    }
    $res = dataUpdate(\tname::distribution_mytrader, $data);
    return $res;
}

/**
 * 建立三级金钱关系   2017-10-15
 * @param $myopenid 我的微信号 $ordernumber 产生关系的订单号  $money 产生关系的金钱 $takemoney 给上三级的金钱数组
 */
function distributionBuildmoney($uid, $myopenid, $orderid, $money, $takemoney = array())
{
    $mytrader = db(\tname::distribution_mytrader)->where(array('uid' => $uid, 'openid' => $myopenid))->find();
    $vip = db(\tname::vip)->where(array('openid' => $myopenid))->find();

    if ($mytrader['firstvipid'] != 0) {
        $data[] = array(
            'uid' => $uid,
            'distributor_vip_id' => $mytrader['firstvipid'],
            'openid' => $myopenid,
            'nickname' => $vip['nickname'],
            'order_id' => $orderid,
            'money' => $money,
            'take_money' => $takemoney[0],
            'rank' => 1,
            'create_time' => time(),
        );
    }
    if ($mytrader['secondvipid'] != 0) {
        $data[] = array(
            'uid' => $uid,
            'distributor_vip_id' => $mytrader['secondvipid'],
            'openid' => $myopenid,
            'nickname' => $vip['nickname'],
            'order_id' => $orderid,
            'money' => $money,
            'take_money' => $takemoney[1],
            'rank' => 2,
            'create_time' => time(),
        );
    }
    if ($mytrader['thirdvipid'] != 0) {
        $data[] = array(
            'uid' => $uid,
            'distributor_vip_id' => $mytrader['thirdvipid'],
            'openid' => $myopenid,
            'nickname' => $vip['nickname'],
            'order_id' => $orderid,
            'money' => $money,
            'take_money' => $takemoney[1],
            'rank' => 3,
            'create_time' => time(),
        );
    }
    if (!empty($data)) {
        $res = db(\tname::distribution_income)->insertAll($data);

        foreach ($data as $k => $v) {
            $distributor = db(tname::vip)->find($v['distributor_vip_id']);
            moneylog($uid, 'distribution', $distributor['openid'], $v['takemoney'], $orderid, 1, '分销佣金');
        }
    }
    return true;
}
//前台换图片路径
function changeurl($imgpath)
{
    $imgpath = get_domain().$imgpath;
    $imgpath=str_replace('\\','/',$imgpath);
    return $imgpath;
}
/**
 * 手机认证
 */
function phone($name,$phone,$people){
    $phone="https://way.jd.com/fegine/pcert?name=".trim($name)."&id=".trim($people)."&phone=".trim($phone)."&appkey=0a370976a80280ab65d709fae7195d35";
    $result=https_request($phone);

    return $result;
}
/**
 * 黑名单认证
 */
function black($name,$phone,$people){
    $url="https://way.jd.com/XinShu/compBQuery?name=".trim($name)."&idCard=".trim($people)."&mobile=".trim($phone)."&bankCardNo=6259565600655656&appkey=0a370976a80280ab65d709fae7195d35";
    $result=https_request($url);

    return $result;
}
function arr(){
     $data=array(
        'a'=>array(
            '严重违法'=>array(
                'blackType'=>'严重违法',
                'blackCount'=>'0',
            ),
            '逾期风险'=>array(
                'blackType'=>'逾期风险',
                'blackCount'=>'0',
            ),
            '诉讼风险'=>array(
                'blackType'=>'诉讼风险',
                'blackCount'=>'0',
            ),
            '潜在风险'=>array(
                'blackType'=>'潜在风险',
                'blackCount'=>'0',
            ),
            '多头贷款'=>array(
                'blackType'=>'多头贷款',
                'blackCount'=>'0',
            ),
        ),
        'b'=>array(
            '严重违法'=>array(
                'a'=>"严重违法",
                'b'=>array(
                    '0'=>array(
                        "blackRiskType"=>"严重违法",
                        "blackFactsType"=>"",
                        "blackFacts"=>"没有查询到相关记录",
                        "blackAmt"=> "",
                        "blackHappenDate"=> "",
                        "blackDurationTime"=> "",
                        "blackPublishSource"=> ""
                    )
                )
            ),
            '逾期风险'=>array(
                'a'=>"逾期风险",
                'b'=>array(
                    '0'=>array(
                        "blackRiskType"=>"逾期风险",
                        "blackFactsType"=>"",
                        "blackFacts"=>"没有查询到相关记录",
                        "blackAmt"=> "",
                        "blackHappenDate"=> "",
                        "blackDurationTime"=> "",
                        "blackPublishSource"=> ""
                    )
                )
            ),
            '诉讼风险'=>array(
                'a'=>"诉讼风险",
                'b'=>array(
                    '0'=>array(
                        "blackRiskType"=>"诉讼风险",
                        "blackFactsType"=>"",
                        "blackFacts"=>"没有查询到相关记录",
                        "blackAmt"=> "",
                        "blackHappenDate"=> "",
                        "blackDurationTime"=> "",
                        "blackPublishSource"=> ""
                    )
                )
            ),
            '潜在风险'=>array(
                'a'=>"潜在风险",
                'b'=>array(
                    '0'=>array(
                        "blackRiskType"=>"潜在风险",
                        "blackFactsType"=>"",
                        "blackFacts"=>"没有查询到相关记录",
                        "blackAmt"=> "",
                        "blackHappenDate"=> "",
                        "blackDurationTime"=> "",
                        "blackPublishSource"=> ""
                    )
                )
            ),
            '7天内贷款数'=>array(
                'a'=>"7天内贷款数",
                'b'=>array(
                    '0'=>array(
                        "blackRiskType"=>"多头借贷",
                        "blackFactsType"=>"7天内贷款数",
                        "blackFacts"=>"没有查询到相关记录",
                        "blackAmt"=> "",
                        "blackHappenDate"=> "",
                        "blackDurationTime"=> "",
                        "blackPublishSource"=> ""
                    )
                )
            ),
            '一个月内贷款数'=>array(
                'a'=>"一个月内贷款数",
                'b'=>array(
                    '0'=>array(
                        "blackRiskType"=>"多头借贷",
                        "blackFactsType"=>"一个月内贷款数",
                        "blackFacts"=>"没有查询到相关记录",
                        "blackAmt"=> "",
                        "blackHappenDate"=> "",
                        "blackDurationTime"=> "",
                        "blackPublishSource"=> ""
                    )
                )
            ),
            '三个月内贷款数'=>array(
                'a'=>"三个月内贷款数",
                'b'=>array(
                    '0'=>array(
                        "blackRiskType"=>"多头借贷",
                        "blackFactsType"=>"三个月内贷款数",
                        "blackFacts"=>"没有查询到相关记录",
                        "blackAmt"=> "",
                        "blackHappenDate"=> "",
                        "blackDurationTime"=> "",
                        "blackPublishSource"=> ""
                    )
                )
            ),
        )
     );
    return $data;
}
//******************************************项目接口*******************************************
#TODO